package com.shujia.flink

import com.shujia.util.Config
import org.apache.flink.runtime.state.StateBackend
import org.apache.flink.runtime.state.filesystem.FsStateBackend
import org.apache.flink.streaming.api.CheckpointingMode
import org.apache.flink.streaming.api.environment.CheckpointConfig.ExternalizedCheckpointCleanup
import org.apache.flink.streaming.api.scala._

abstract class FlinkTool {
  var env: StreamExecutionEnvironment = _
  var isLocal: Boolean = Config.getBoolean("is.local")

  def main(args: Array[String]): Unit = {
    /**
      * 1、创建flink环境
      *
      */

    env = StreamExecutionEnvironment.getExecutionEnvironment


    //如果是本地不执行checkpoint,不是本地在执行checkpoint
    if (!isLocal) {
      checkpoint()
    }


    run(args)

  }

  def run(args: Array[String])


  def checkpoint(): Unit = {
    // 每 1000ms 开始一次 checkpoint
    env.enableCheckpointing(30000)

    // 高级选项：

    // 设置模式为精确一次 (这是默认值)
    env.getCheckpointConfig.setCheckpointingMode(CheckpointingMode.EXACTLY_ONCE)

    // 确认 checkpoints 之间的时间会进行 500 ms
    env.getCheckpointConfig.setMinPauseBetweenCheckpoints(500)

    // Checkpoint 必须在一分钟内完成，否则就会被抛弃
    env.getCheckpointConfig.setCheckpointTimeout(120000)

    // 同一时间只允许一个 checkpoint 进行
    env.getCheckpointConfig.setMaxConcurrentCheckpoints(1)

    //当任务取消的时候是否保留checkpoint,默认不保留
    env.getCheckpointConfig.enableExternalizedCheckpoints(ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION)
    /**
      * 指定保存状态的位置
      *
      */
    //文件系统的状态后端，可以说hdfs
    val stateBackend: StateBackend = new FsStateBackend(
      "hdfs://master:9000/data/flink/checkpoint",
      true
    )
    env.setStateBackend(stateBackend)

  }


}
